﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using filmquiz.Src.Domain;
using filmquiz.Src.Login;
using filmquiz.Src.SessionHandle;
using filmquiz.Src.DatabaseAccess;

public partial class Register : System.Web.UI.Page
{
    private LoginController loginController = new LoginController();
    private SessionController sessionController = new SessionController();

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    private void Page_PreRender(object sender, System.EventArgs e)
    {
        if ((bool)Session["loggedIn"])
        {
            notLoggedInContainer.Visible = false;
            loggedInContainer.Visible = true;
        }
        else
        {
            notLoggedInContainer.Visible = true;
            loggedInContainer.Visible = false;

            registerLabel.Text = QuizHelper.getInstance().getCreateUserText();
        }
    }

    protected void createUserButton_Click(object sender, EventArgs e)
    {
        if (!loginController.DoesUserExist(createUsernameText.Text))
        {
            String password = createPasswordText.Text;
            User newUser = new User();
            newUser.setName(createUsernameText.Text);
            newUser.setEmail(emailText.Text);
            UserHelper.getInstance().saveUser(newUser, password);
            if (loginController.DoLogin(newUser.getName(), password))
            {
                sessionController.updateSession(loginController.getLoggedInUser(), Session);
                CookieHelper.getInstance().createLoginCookies(loginController.getLoggedInUser(), Response);
                createUsernameText.Text = "";
                emailText.Text = "";
            }
        }
        else
        {
            userExistsLabel.Text = "Brugernavnet er allerede optaget. Hvis du har glemt dit password, kan du bruge linket under loginfelterne til at få det tilsendt igen.";
        }
    }

    protected void saveChangesButton_Click(object sender, EventArgs e)
    {
        UserHelper.getInstance().saveNewPassword((User)Session["user"], changePassword1.Text);
    }
}
